package com.h3c.nem.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.h3c.nem.dto.TbWorkSecurityMiddleDTO;
import com.h3c.nem.entity.TbOfferWorker;
import com.h3c.nem.mapper.TbWorkSecurityMiddleMapper;
import com.h3c.nem.entity.TbWorkSecurityMiddle;
import com.h3c.nem.service.CommService;
import com.h3c.nem.service.ITbPersonnelRegisterMiddleService;
import com.h3c.nem.service.ITbOfferWorkerService;
import com.h3c.nem.service.ITbWorkSecurityMiddleService;
import com.h3c.nem.utils.AppBusinessException;
import com.h3c.nem.utils.CommonUtil;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 实现类
 *
 * @author chenyifan
 * @since 2022-06-16 09:53:01
 */
@Service
@AllArgsConstructor
public class TbWorkSecurityMiddleServiceImpl extends ServiceImpl<TbWorkSecurityMiddleMapper, TbWorkSecurityMiddle> implements ITbWorkSecurityMiddleService {

    @Autowired
    TbWorkSecurityMiddleMapper workSecurityMiddleMapper;

    @Autowired
    CommService commService;

    private final ITbPersonnelRegisterMiddleService personnelRegisterMiddleService;

    private final ITbOfferWorkerService offerWorkerService;

    @Override
    public List<String> getOptionalCoverage() {
        ArrayList<String> result = new ArrayList<>();
        TbOfferWorker offerWorker = offerWorkerService.getById(CommonUtil.getActivUser().getUserId());
        String placeOfWork = offerWorker.getWorkCity();
        if (StringUtils.hasText(offerWorker.getOuterCity())) {
            placeOfWork = offerWorker.getOuterCity();
        }
        //如工作履行地(如有外派工作地时，用外派工作地)为附件表格中的地级城市，因社保公积金参保地无法覆盖，读取省会城市
        TbWorkSecurityMiddle workSecurityMiddle = getOne(new QueryWrapper<TbWorkSecurityMiddle>().lambda()
                .eq(TbWorkSecurityMiddle::getWorkCity, placeOfWork)
        );
        //如果属于地级城市
        if (Objects.nonNull(workSecurityMiddle)) {
            placeOfWork = workSecurityMiddle.getSecurityCity();
        }
        if ((placeOfWork.equals(TbWorkSecurityMiddle.SPECIAL_LOCAL_2_1) || placeOfWork.equals(TbWorkSecurityMiddle.SPECIAL_LOCAL_2_2))
                && !offerWorker.getPersonnelRangeCode().equals(TbWorkSecurityMiddle.SPECIAL_COMPANY_3_1)) {
            //如工作履行地(如有外派工作地时，用外派工作地)为杭州、北京，只保留劳动合同注册地选项    2022/8/4更改为 如工作履行地(如有外派工作地时，用外派工作地)为杭州、北京，签署公司非新华三技术有限公司，只保留劳动合同注册地选项
            result.add(personnelRegisterMiddleService.getRegistrationByPersonnelScope(offerWorker.getPersonnelRangeCode()));
        } else if (placeOfWork.equals(TbWorkSecurityMiddle.SPECIAL_LOCAL_3) &&
                !offerWorker.getPersonnelRangeCode().equals(TbWorkSecurityMiddle.SPECIAL_COMPANY_3_1) &&
                !offerWorker.getPersonnelRangeCode().equals(TbWorkSecurityMiddle.SPECIAL_COMPANY_3_2)) {
            //如工作履行地(如有外派工作地时，用外派工作地)为石家庄，若签署公司非新华三技术有限公司/紫光华山科技有限公司这2家公司，只保留劳动合同注册地选项
            result.add(personnelRegisterMiddleService.getRegistrationByPersonnelScope(offerWorker.getPersonnelRangeCode()));
        } else if (placeOfWork.equals(TbWorkSecurityMiddle.SPECIAL_LOCAL_4) &&
                !offerWorker.getPersonnelRangeCode().equals(TbWorkSecurityMiddle.SPECIAL_COMPANY_3_1)) {
            //如工作履行地(如有外派工作地时，用外派工作地)为深圳，若签署公司非新华三技术有限公司公司，只保留劳动合同注册地选项
            result.add(personnelRegisterMiddleService.getRegistrationByPersonnelScope(offerWorker.getPersonnelRangeCode()));
        }else if(placeOfWork.equals(TbWorkSecurityMiddle.SPECIAL_LOCAL_5) || placeOfWork.equals(TbWorkSecurityMiddle.SPECIAL_LOCAL_6)
                || placeOfWork.equals(TbWorkSecurityMiddle.SPECIAL_LOCAL_7) || placeOfWork.equals(TbWorkSecurityMiddle.SPECIAL_LOCAL_8)
                || placeOfWork.equals(TbWorkSecurityMiddle.SPECIAL_LOCAL_9) || placeOfWork.equals(TbWorkSecurityMiddle.SPECIAL_LOCAL_10)){
            //如工作履行地(如有外派工作地时，用外派工作地)为呼和浩特,广州、东莞、佛山、中山、珠海，只保留劳动合同注册地选项
            result.add(personnelRegisterMiddleService.getRegistrationByPersonnelScope(offerWorker.getPersonnelRangeCode()));
        } else {
            //获取劳动合同注册地
            result.add(personnelRegisterMiddleService.getRegistrationByPersonnelScope(offerWorker.getPersonnelRangeCode()));
            result.add(placeOfWork);
        }
        return result.stream().filter(s->StringUtils.hasText(s)).distinct().collect(Collectors.toList());
    }

    @Override
    public List<TbWorkSecurityMiddleDTO> selectFuzzyByDto(TbWorkSecurityMiddleDTO dto) {
        List<TbWorkSecurityMiddle> workSecurityMiddles = workSecurityMiddleMapper.selectList(new QueryWrapper<TbWorkSecurityMiddle>().lambda()
                .like(!StringUtils.isEmpty(dto.getWorkCity()), TbWorkSecurityMiddle::getWorkCity, dto.getWorkCity())
                .like(!StringUtils.isEmpty(dto.getSecurityCity()), TbWorkSecurityMiddle::getSecurityCity, dto.getSecurityCity()));
        List<TbWorkSecurityMiddleDTO> workSecurityMiddleDTOList = workSecurityMiddles.stream().map(tbWorkSecurityMiddle -> {
            TbWorkSecurityMiddleDTO workSecurityMiddleDTO = new TbWorkSecurityMiddleDTO();
            BeanUtils.copyProperties(tbWorkSecurityMiddle, workSecurityMiddleDTO);
            return workSecurityMiddleDTO;
        }).collect(Collectors.toList());
//        List<TbWorkSecurityMiddle> workSecurityMiddleList = workSecurityMiddleMapper.queryListByFuzzy(JSONObject.parseObject(JSONObject.toJSONString(dto), TbWorkSecurityMiddle.class));
//        return JSONArray.parseArray(JSONArray.toJSONString(workSecurityMiddleList), TbWorkSecurityMiddleDTO.class);
        return workSecurityMiddleDTOList;
    }

    @Override
    public Integer insertDto(TbWorkSecurityMiddleDTO dto) {
        TbWorkSecurityMiddle workSecurityMiddle = getTbWorkSecurityMiddle(dto);
        return workSecurityMiddleMapper.insert(workSecurityMiddle);
    }

    @Override
    public Integer updateDto(TbWorkSecurityMiddleDTO dto) {
        TbWorkSecurityMiddle workSecurityMiddle = getTbWorkSecurityMiddle(dto);
        return workSecurityMiddleMapper.updateById(workSecurityMiddle);
    }

    /**
     * 判断数据是否存在
     * @param dto
     * @return
     */
    private TbWorkSecurityMiddle getTbWorkSecurityMiddle(TbWorkSecurityMiddleDTO dto) {
        QueryWrapper<TbWorkSecurityMiddle> queryWrapper = Wrappers.query();
        queryWrapper.eq("work_city", dto.getWorkCity())
                .eq("security_city", dto.getSecurityCity());
        TbWorkSecurityMiddle workSecurityMiddle = workSecurityMiddleMapper.selectOne(queryWrapper);
        if (workSecurityMiddle != null){
            throw new AppBusinessException("该条数据已存在，请重新输入");
        }
        workSecurityMiddle = new TbWorkSecurityMiddle();
        BeanUtils.copyProperties(dto, workSecurityMiddle);
        return workSecurityMiddle;
    }

    @Override
    public Integer deleteDto(TbWorkSecurityMiddleDTO dto) {
        return workSecurityMiddleMapper.deleteById(dto.getId());
    }

    @Override
    public Integer importUserNew(MultipartFile file) {
        String fileContent = commService.parseExcelByTemplate("WORK_SECURITY_MIDDLE_IMPORT", file);
        JSONArray jsonArray = JSONArray.parseArray(fileContent);
//        List<TbWorkSecurityMiddleDTO> workSecurityMiddleDTOList = selectFuzzyByDto(new TbWorkSecurityMiddleDTO()); //数据库现存工作常驻地和参保地映射关系
//        List<TbWorkSecurityMiddleDTO> workSecurityMiddleDTOS = new ArrayList<>();
        Integer num = 0;
        for (Object jsonObj : jsonArray) {
            JSONObject jsonObject = JSONObject.parseObject(jsonObj.toString());
            TbWorkSecurityMiddleDTO workSecurityMiddleDTO = JSONObject.parseObject(jsonObject.toJSONString(), TbWorkSecurityMiddleDTO.class);
            if (!StringUtils.hasText(workSecurityMiddleDTO.getWorkCity())){
                continue;
            }
            QueryWrapper<TbWorkSecurityMiddle> queryWrapper = Wrappers.query();
            queryWrapper.eq("work_city", workSecurityMiddleDTO.getWorkCity())
                    .eq("security_city", workSecurityMiddleDTO.getSecurityCity());
            TbWorkSecurityMiddle workSecurityMiddle = workSecurityMiddleMapper.selectOne(queryWrapper);
            if (workSecurityMiddle != null){
                continue;
            }
            workSecurityMiddle = new TbWorkSecurityMiddle();
            BeanUtils.copyProperties(workSecurityMiddleDTO, workSecurityMiddle);
            if (workSecurityMiddleDTO.getSecurityCity().equals(TbWorkSecurityMiddle.SECURITYCITY)){
                workSecurityMiddle.setSecurityCity("");
            }
            num = num + workSecurityMiddleMapper.insert(workSecurityMiddle);

        }
        return num;
    }

}

